import Dialog from '@vant/weapp/dialog/dialog';

Page({
  data: {
    purpose: '',
    diagnosis: '',
    diagnosisLength: 0,
    name: '',
    gender: '',
    ageGroup: '',
    region: ['', ''],
    phone: '',
    phoneError: '',
    department: '',
    doctor: '',
    referrerName: '',
    referrerType: '',
    referrerPhone: '',
    referrerPhoneError: '',
    captchaUrl: 'path/to/captcha/image',
    verifyCode: '',
    counting: false,
    countDown: 60,
    privacyAgreed: false,
    captchaText: '',
    showModal: false
  },

  onGenderChange(e) {
    this.setData({
      gender: e.detail.value
    });
  },

  onAgeGroupChange(e) {
    this.setData({
      ageGroup: e.detail.value
    })
  },

  onCityChange(e) {
    const region = e.detail.value;
    this.setData({
      region: [region[0], region[1]]
    });
  },

  onPurposeChange(e) {
    this.setData({
      purpose: e.detail.value
    })
  },

  onDiagnosisInput(e) {
    const diagnosis = e.detail.value
    this.setData({
      diagnosis,
      diagnosisLength: diagnosis.length
    })
  },

  validatePhone(e) {
    const phone = e.detail.value
    const phoneReg = /^1[3-9]\d{9}$/

    // 如果输入为空，清除错误提示
    if (!phone) {
      this.setData({
        phoneError: ''
      })
      return
    }

    // 验证手机号格式
    if (!phoneReg.test(phone)) {
      this.setData({
        phoneError: '请输入正确的手机号码'
      })
      return false
    } else {
      this.setData({
        phoneError: ''
      })
      return true
    }
  },

  onReferrerTypeChange(e) {
    this.setData({
      referrerType: e.detail.value
    })
  },

  validateReferrerPhone(e) {
    const phone = e.detail.value
    const phoneReg = /^1[3-9]\d{9}$/

    if (!phone) {
      this.setData({
        referrerPhoneError: ''
      })
      return
    }

    if (!phoneReg.test(phone)) {
      this.setData({
        referrerPhoneError: '请输入正确的手机号码'
      })
      return false
    } else {
      this.setData({
        referrerPhoneError: ''
      })
    }
  },

  generateCaptchaText() {
    const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    let captcha = '';
    for (let i = 0; i < 4; i++) {
      captcha += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return captcha;
  },

  drawCaptcha() {
    const captchaText = this.generateCaptchaText();
    this.setData({ captchaText });

    const query = wx.createSelectorQuery();
    query.select('#captcha')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');

        // 设置canvas大小
        canvas.width = 200;
        canvas.height = 80;

        // 填充背景
        ctx.fillStyle = '#f5f5f5';
        ctx.fillRect(0, 0, 200, 80);

        // 绘制文字
        ctx.fillStyle = '#333';
        ctx.font = 'bold 38px Arial';
        ctx.textBaseline = 'middle';
        
        // 随机位置绘制每个字符
        for (let i = 0; i < captchaText.length; i++) {
          const x = 40 + i * 40 + Math.random() * 10;
          const y = 40 + Math.random() * 10;
          const rotate = (Math.random() - 0.5) * 0.3;
          ctx.save();
          ctx.translate(x, y);
          ctx.rotate(rotate);
          ctx.fillText(captchaText[i], 0, 0);
          ctx.restore();
        }

        // 绘制干扰线
        for (let i = 0; i < 3; i++) {
          ctx.beginPath();
          ctx.strokeStyle = `rgba(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255},0.5)`;
          ctx.moveTo(Math.random() * 200, Math.random() * 80);
          ctx.lineTo(Math.random() * 200, Math.random() * 80);
          ctx.stroke();
        }
      });
  },

  refreshCaptcha() {
    this.drawCaptcha();
  },

  validateCaptcha(inputCode) {
    return inputCode.toLowerCase() === this.data.captchaText.toLowerCase();
  },

  getVerifyCode() {
    if (this.data.counting) return;
    
    // 验证手机号
    if (!this.validateReferrerPhone({ detail: { value: this.data.referrerPhone } })) {
      return;
    }

    if (!this.validateCaptcha(this.data.captcha)) {
      wx.showToast({
        title: '图形验证码错误',
        icon: 'none'
      });
      return;
    }

    // 开始倒计时
    this.setData({
      counting: true
    })

    let count = 60
    const timer = setInterval(() => {
      count--
      this.setData({
        countDown: count
      })
      if (count === 0) {
        clearInterval(timer)
        this.setData({
          counting: false,
          countDown: 60
        })
      }
    }, 1000)

    // 发送验证码请求
    // ...
  },

  onPrivacyChange(e) {
    this.setData({
      privacyAgreed: e.detail.value.length > 0
    })
  },

  showPrivacyPolicy() {
    this.setData({
      showModal: true
    });
  },

  closeModal() {
    this.setData({
      showModal: false
    });
  },

  confirmModal() {
    this.setData({
      showModal: false,
      privacyAgreed: true
    });
  },

  // 校验表单
  validateForm() {
    const {
      purpose,
      name,
      gender,
      ageGroup,
      region,
      phone,
      department,
      doctor,
      referrerName,
      referrerType,
      referrerPhone,
      captcha,
      verifyCode,
      privacyAgreed
    } = this.data;

    // 定义必填字段和对应的提示文字
    const requiredFields = [
      { field: 'purpose', name: '转诊目的', selector: '#purpose-group' },
      { field: 'name', name: '患者姓名', selector: '#patient-name' },
      { field: 'gender', name: '患者性别', selector: '#patient-gender' },
      { field: 'ageGroup', name: '患者年龄', selector: '#patient-age' },
      { field: 'region[1]', name: '患者所在城市', selector: '#patient-city' },
      { field: 'phone', name: '患者电话', selector: '#patient-phone' },
      { field: 'department', name: '期望转入科室', selector: '#department' },
      { field: 'doctor', name: '期望诊疗医生', selector: '#doctor' },
      { field: 'referrerName', name: '推荐人姓名', selector: '#referrer-name' },
      { field: 'referrerType', name: '推荐人身份', selector: '#referrer-type' },
      { field: 'referrerPhone', name: '推荐人手机号', selector: '#referrer-phone' },
    ];

    // 检查必填字段
    for (const item of requiredFields) {
      let value = item.field.includes('[') ?
        this.data[item.field.split('[')[0]][item.field.split('[')[1].replace(']', '')] :
        this.data[item.field];

      if (!value) {
        // 使用同步方式获取元素位置
        const query = wx.createSelectorQuery();
        query.select(item.selector).boundingClientRect(rect => {
          if (rect) {
            // 使用 getSystemInfoSync 获取窗口信息
            const windowInfo = wx.getWindowInfo();
            // 滚动到未填写字段的位置
            wx.pageScrollTo({
              scrollTop: rect.top + windowInfo.windowHeight / 2 + 700, // 确保未填写字段在视口中可见
              duration: 300
            });
          }
        }).exec();

        // 显示提示
        wx.showToast({
          title: `请填写${item.name}`,
          icon: 'none'
        });

        return false; // 终止校验
      }
    }

    // 校验手机号格式
    if (!this.validatePhone({ detail: { value: phone } })) {
      wx.showToast({
        title: '请输入正确的患者手机号码',
        icon: 'none'
      });
      return false;
    }

    if (!this.validateReferrerPhone({ detail: { value: referrerPhone } })) {
      wx.showToast({
        title: '请输入正确的推荐人手机号码',
        icon: 'none'
      });
      return false;
    }

    // 校验隐私政策
    if (!privacyAgreed) {
      wx.showToast({
        title: '请同意双向转诊声明',
        icon: 'none'
      });
      return false;
    }

    return true; // 校验通过
  },

  // 提交方法改回同步
  submitForm() {
    if (!this.validateForm()) {
      return;
    }

    // 验证通过，提交表单
    console.log('表单数据：', this.data);

    wx.showToast({
      title: '提交成功',
      icon: 'success'
    });
  },

  navigateToDepartment() {
    wx.navigateTo({
      url: '/pages/select-department/select-department'
    });
  },

  navigateToDoctor() {
    wx.navigateTo({
      url: '/pages/select-doctor/select-doctor'
    });
  },

  onLoad() {
    // 页面加载时生成验证码
    this.drawCaptcha();
  },

  onButtonClick() {
    Toast('按钮被点击了！');
  },

  showStatement() {
    Dialog.confirm({
      title: '双向转诊声明',
      message: '这是南京有的大学张发明医生团队依托中国菌群移植平台设计的快捷推荐就医渠道，旨在帮助患者能够快速就医。需要体统初步信息，这些信息务必真实准确。\n我知晓，这不带便疾病诊治，不承担此过程可能发生的任何风险责任。这只是提供一个帮助他人的渠道，而且全过程免费。毫无疑问，我和被推荐患者的信息都必须报名，属于隐私信息。\n我知晓以上信息并同意提供推荐就医的信息。',
      messageAlign: 'left',
      confirmButtonText: "我同意",
      cancelButtonText: "我拒绝",
    }).then(() => {
      this.setData({ privacyAgreed: true })
    }).catch(() => {
      this.setData({ privacyAgreed: false })
    });
  },
}) 